import { request } from "../../request/index.js";
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';

// components/HistoryAdress/HistoryAdress.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    animalId: {
      type: Number,
      value: -1
    },
    isAdd: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    now: '2021-11-25',
    date: '2021-10-23',
    multiArray: [['猫', '狗'], ['大猫', '中猫', '小猫']],
    multiIndex: [0, 0],
    array: ['十分健康', '一般健康', '不健康', '有明显外伤', '精神萎靡', '不明确'],
    index: 0,
    areaMultiArray: [['西区', '东区', '教学区', '运动场', '南亭'], ['一栋', '二栋', '三栋', '四栋']],
    areaMultiIndex: [0, 0],
    additionalInformation: '',
    animalNickname: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 设置时间
    bindDateChange: function(e) {
      // 有超出规定时间bug，需要手动判断是否超出时间
      if (new Date(e.detail.value.replaceAll('-','/')).getTime() > new Date(this.data.now.replaceAll('-','/')).getTime()) {
        wx.showToast({
          title: '超出今天的日期',
          icon: 'error',
          duration: 1500
        })
        return
      }
      this.setData({
        date: e.detail.value
      })
    },

    // 品种
    bindMultiPickerChange: function (e) {
      this.setData({
        multiIndex: e.detail.value
      })
    },
    bindMultiPickerColumnChange: function (e) {
      var data = {
        multiArray: this.data.multiArray,
        multiIndex: this.data.multiIndex
      };
      data.multiIndex[e.detail.column] = e.detail.value
      console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
      switch (e.detail.column) {
        case 0:
          switch (data.multiIndex[0]) {
            case 0:
              data.multiArray[1] = ['大猫', '中猫', '小猫']
              data.multiIndex[1] = 0
              break
            case 1:
              data.multiArray[1] = ['大狗', '中狗', '小狗']
              data.multiIndex[1] = 0
              break
          }
      }
      this.setData(data);
    },

    // 健康状况
    bindPickerChange: function(e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      this.setData({
        index: e.detail.value
      })
    },

    // 地区
    areaBindMultiPickerChange: function (e) {
      this.setData({
        areaMultiIndex: e.detail.value
      })
    },
    areaBindMultiPickerColumnChange: function (e) {
      var data = {
        areaMultiArray: this.data.areaMultiArray,
        areaMultiIndex: this.data.areaMultiIndex
      };
      data.areaMultiIndex[e.detail.column] = e.detail.value
      switch (e.detail.column) {
        case 0:
          switch (data.areaMultiIndex[0]) {
            case 0:
              data.areaMultiArray[1] = ['一栋', '二栋', '三栋', '四栋']
              data.areaMultiIndex[1] = 0
              break
            case 1:
              data.areaMultiArray[1] = ['一栋', '二栋', '三栋', '四栋']
              data.areaMultiIndex[1] = 0
              break
            case 2:
              data.areaMultiArray[1] = ['一栋', '二栋', '三栋', '四栋', '五栋', '六栋']
              data.areaMultiIndex[1] = 0
              break
            case 3:
              data.areaMultiArray[1] = ['足球场', '篮球场', '排球场', '板球场']
              data.areaMultiIndex[1] = 0
              break
            case 4:
              data.areaMultiArray[1] = ['南亭']
              data.areaMultiIndex[1] = 0
              break

          }
      }
      this.setData(data);
    },

    // 上传须知
    handleKnow () {
      wx.showModal({
        title: '上传须知',
        content: '须知什么的不知道怎么编...',
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F'
      });
    },

    // 数据回显
    async dataReshow () {
      const res = await request({
        url: '/animal/queryOneAnimal',
        data: {
          animalId: this.properties.animalId
        }
      })
      if (res.resultTypeCode == 200) {
        let typeArr = [['猫', '狗'], []]
        switch (res.data.animalTypeIndex.split('-')[0] - 0) {
          case 0:
            typeArr[1] = ['大猫', '中猫', '小猫']
            break
          case 1:
            typeArr[1] = ['大狗', '中狗', '小狗']
            break
        }
        let areaArr = [['西区', '东区', '教学区', '运动场', '南亭'], []]
        switch (res.data.addressFirstIndex) {
          case 0:
            areaArr[1] = ['一栋', '二栋', '三栋', '四栋']
            break
          case 1:
            areaArr[1] = ['一栋', '二栋', '三栋', '四栋']
            break
          case 2:
            areaArr[1] = ['一栋', '二栋', '三栋', '四栋', '五栋', '六栋']
            break
          case 3:
            areaArr[1] = ['足球场', '篮球场', '排球场', '板球场']
            break
          case 4:
            areaArr[1] = ['南亭']
            break
        }
        this.setData ({
          date: res.data.updateTime.split('T')[0],
          additionalInformation: res.data.additionalInformation,
          areaMultiIndex: [res.data.addressFirstIndex, res.data.addressSecondIndex],
          areaMultiArray: areaArr,
          animalNickname: res.data.animalNickname,
          multiIndex: [res.data.animalTypeIndex.split('-')[0] - 0, res.data.animalTypeIndex.split('-')[0] - 1],
          multiArray: typeArr,
          index: res.data.healthIndex,
        })
        console.log(this.data)
      }
    },

    // 提交表单
    formSubmit (e) {
      const myUploadPics = this.selectComponent('#myUploadPics')
      const animalImgList = myUploadPics.getImgs()
      if (animalImgList.length == 0) {
        wx.showToast({
          title: '至少上传一张图片',
          icon: 'error',
          duration: 1000,
        })
        return
      }
      if (e.detail.value.animalNickname.trim().length == 0) {
        wx.showToast({
          title: '昵称不能为空',
          icon: 'error',
          duration: 1000,
        })
        return
      }
      wx.showModal({
        title: '确定提交表单？',
        showCancel: true,
        cancelText: '取消',
        cancelColor: '#000000',
        confirmText: '确定',
        confirmColor: '#3CC51F',
        success: async (result) => {
          if(result.confirm){
            animalImgList.forEach(async (v, i) => {
              await wx.uploadFile({
                url: 'http://1.14.202.218:7777/fileoss',
                filePath: v.path,
                name: 'file',
                formData: {},
                success: (res)=>{
                  animalImgList[i].path = JSON.parse(res.data).data
                }
              })
            })

            const obj = {
              animalImgList,
              animalNickname: e.detail.value.animalNickname,
              updateTime: this.data.date,
              health: this.data.array[this.data.index],
              healthIndex: this.data.index + "",
              animalType: this.data.multiArray[0][this.data.multiIndex[0]] + "-" + this.data.multiArray[1][this.data.multiIndex[1]],
              animalTypeIndex: this.data.multiIndex[0] + '/' + this.data.multiIndex[1],
              lastAddress: this.data.areaMultiArray[0][this.data.areaMultiIndex[0]] + "-" + this.data.areaMultiArray[1][this.data.areaMultiIndex[1]],
              lastAddressFirstIndex: this.data.areaMultiIndex[0],
              lastAddressSecondIndex: this.data.areaMultiIndex[1],
              additionalInformation: e.detail.value.additionalInformation
            }

            console.log(obj)

            const res = await request({
              url: '/application/apply',
              method: 'post',
              header: {
                'content-type':'application/json',
                token: wx.getStorageSync('token')
              },
              data: {
                application: JSON.stringify({
                  information: JSON.stringify(obj),
                  type: 0
                })
              }
            })
            
            console.log(res)

            wx.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 1000
            });

            this.triggerEvent("refreshPage")    
          }
        }
      })
    },

  },

  // 生命周期
  lifetimes: {
    attached () {
      // 在组件实例进入页面节点树时执行
      let date = new Date()
      this.setData ({
        now: date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate(),
        date: date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()
      })
      if (!this.properties.isAdd) {
        this.dataReshow ()
      }
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  }
})
